package com.service.lx;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dao.lx.FunctionDAO;
import com.dao.lx.FunctionalclassifyDAO;
import com.dao.lx.RoleDAO;
import com.dao.lx.UserDAO;
import com.entity.Function;
import com.entity.Functionalclassify;
import com.entity.Role;
import com.entity.User;
import com.service.ServiceException;
import com.utils.RoleFunctionItem;


@Service
@Transactional(rollbackFor = Exception.class)
public class RoleService {
	@Autowired
	private FunctionalclassifyDAO functionalclassifyDAO;
	@Autowired
	private FunctionDAO functionDAO;
	@Autowired
	private RoleDAO roleDAO;
	@Autowired
	private UserDAO userDAO;
	/**
	 * 添加/修改/逻辑删除
	 * @param role
	 * @throws ServiceException
	 */
	public void addAndUpdateRole(Role role) throws ServiceException{
		try {
			Role role2=roleDAO.findOne(role.getRoleId());
			if(role2==null){
				role.setRoleIfdelete(new BigDecimal(1));
			}
			role.setRoleIntodate(new Date());
			roleDAO.save(role);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	/**
	 * 删除
	 * @param roleid
	 * @throws ServiceException
	 */
	public void deleteRole(Long roleid) throws ServiceException{
		try {
			roleDAO.delete(roleid);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	

	/**
	 * 逻辑删除
	 * @param roleId
	 */
	public void UpdateFunctionIfdelete(Long roleId) {
		Role role = roleDAO.findOne(roleId);
		role.setRoleIfdelete(new BigDecimal(0));
		addAndUpdateRole(role);
	}
	
	/**
	 * 批量删除
	 * @param userIds
	 */
	public void deletArrIfDelete(List<Long> roleIds) {
		if(roleIds != null) {
			for(Long roleId: roleIds) {
				Role role = roleDAO.findOne(roleId);
				role.setRoleIfdelete(new BigDecimal(0));
				addAndUpdateRole(role);
			}
		}
	}
	/**
	 * 单条查询
	 * @param userid
	 * @return
	 */
	public Role findOne(Long roleid) {
		return roleDAO.findOne(roleid);
	}


	/**
	 * 分页查询角色
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	public Page<Role> findRoles(Integer curpage, Integer pagesize){
		return roleDAO.findRoles(new PageRequest(curpage-1, pagesize));
	}
	
	/**
	 * 条件分页查询
	 * @param roleName
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	public Page<Role> getRolesByWhere(String roleName, Integer curpage, Integer pagesize){
		return roleDAO.findByRoleName(roleName, new PageRequest(curpage-1, pagesize));
	}
	

	/**
	 * 获取所有的功能
	 * @return
	 */
	public List<RoleFunctionItem> queryAllFunctions(){
		List<Functionalclassify> functionalclassify = (List<Functionalclassify>) functionalclassifyDAO.findAll();
		List<RoleFunctionItem> functionItems = new ArrayList<>();
		if(functionalclassify != null) {
			for(Functionalclassify type: functionalclassify) {
				RoleFunctionItem item = new RoleFunctionItem(-type.getFunctionalclassifyId(), type.getFunctionalclassifyName(), true);
				functionItems.add(item);
				List<Function> functions = type.getFunctions();
				if(functions != null) {
					for(Function f: functions) {
						RoleFunctionItem item2 = new RoleFunctionItem(f.getFunctionId(), f.getFunctionName(), false);
						functionItems.add(item2);
					}
				}
			}
		}
		return functionItems;
	}
	
	/**
	 * 获取指定角色所拥有的功能id集合
	 * @param roleId
	 * @return
	 */
	public List<Long> getFunctionsByRole(Long roleId){
		Role role = roleDAO.findById(roleId);
		List<Function> functions = role.getFunctions();
		List<Long> list = new ArrayList<>();
		if(functions != null) {
			for(Function f: functions) {
				list.add(f.getFunctionId());
			}
		}
		return list;
	}
	
	/**
	 * 给角色授权
	 * @param map
	 * @param functionIds
	 */
	public void grantForRole(Map map) {
		Integer roleId = (Integer) map.get("roleId");
		List<Long> functionIds = JSONObject.parseArray(((JSONArray) map.get("functionIds")).toString(), Long.class);
		Role role = roleDAO.findById(roleId.longValue());
		if(role.getFunctions() != null) {
			role.getFunctions().clear();
		}
		if(functionIds != null) {
			for(Long fid: functionIds) {
				Function function = functionDAO.findOne(fid);
				if(role.getFunctions() != null) {
					role.getFunctions().add(function);
				}
			}
		}
	}
	
	/**
	 * 获取指定用户拥有的功能
	 * @param userId
	 * @return
	 */
	public List<Long> getFunctionsByUserId(Long userId){
		User user = userDAO.findOne(userId);
		List<Long> list = new ArrayList<>();
		if(user != null) {
			List<Role> roles = user.getRoles();
			if(roles != null) {
				for(Role role: roles) {
					List<Function> functions = role.getFunctions();
					for(Function function: functions) {
						list.add(function.getFunctionId());
					}
				}
			}
		}
		return list;
	}

	/**
	 * 查询
	 * @param field
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	public Page<Role> findRoles(String field, Integer curpage, Integer pagesize) {
		String str;
		if(field.startsWith("roleName")){
			str=field.replace("roleName", "");
			return getRolesByWhere(str, curpage, pagesize);
		}else{
			return findRoles(curpage, pagesize);
		}
	}
}
